var commonNamesCount = 1;

var featureAdded = false;

var mapAreaOrigTop = 0;

// Structures
var commonname = function(){
  this.name = '';
  this.language = '';
  this.region = '';
}

var location_details = function() {
  this.country = '';
  this.region = '';
  this.city = '';
  this.locality = '';
}

var waterbody = function() {
  this.type = '';
  this.name = '';
}

var observer_details = function() {
  this.fname = '';
  this.lname = '';
  this.emailid = '';
  this.affiliation = '';
  this.address = '';
  this.phone = '';
  this.mobile = '';
}

var allowedImageExt = [
  'jpg',
  'jpeg',
];

// Functions
function onMapInitComplete() {
  mapportal.showEditingToolbar();
  mapportal.onAddFeatureClearPreviousFeatures = 1;
  if (typeof(topo_WKT) != 'undefined') {
    mapportal.addFeatureFromWKT(topo_WKT);
  }
}

function onFeatureAddedOnMap(topology) {
  featureAdded = true;
  jQuery("#edit-wo-topology").val(topology);
}

function showMapArea(flag) {
  if (flag == null) {
    flag = true;
  }
  if (flag == true) {
    jQuery("#mapArea").show();
  } else {
    jQuery("#mapArea").hide();
  }
}

function toggleExactDate(show) {
  if (show) {
    jQuery("#edit-wo-date-range-wrapper").show();
    jQuery("#edit-wo-on-date-wrapper").hide();
  } else {
    jQuery("#edit-wo-date-range-wrapper").hide();
    jQuery("#edit-wo-on-date-wrapper").show();
  }
}

function toggleExactTime(show) {
  if (show) {
    jQuery("#edit-wo-exact-time-wrapper").show();
    jQuery("#edit-wo-part-of-day-wrapper").hide();
  } else {
    jQuery("#edit-wo-exact-time-wrapper").hide();
    jQuery("#edit-wo-part-of-day-wrapper").show();
  }
}

function toggleWaterbodyInfo(show) {
  if (show) {
    jQuery("#edit-wo-waterbody-type-wrapper").show();
    jQuery("#edit-wo-waterbody-name-wrapper").show();
  } else {
    jQuery("#edit-wo-waterbody-type-wrapper").hide();
    jQuery("#edit-wo-waterbody-name-wrapper").hide();
  }
}

function toggleOtherObserverDetails(show) {
  if (show) {
    jQuery("#fieldset_other_observer").show();
  } else {
    jQuery("#fieldset_other_observer").hide();
  }
}

function resetOtherObserverDetailsForm() {
  jQuery("#edit-wo-other-observer-first-name").val("");
  jQuery("#edit-wo-other-observer-last-name").val("");
  jQuery("#edit-wo-other-observer-affiliation").val("");
  jQuery("#edit-wo-other-observer-address1").val("");
  jQuery("#edit-wo-other-observer-address2").val("");
  jQuery("#edit-wo-other-observer-city").val("");
  jQuery("#edit-wo-other-observer-region").val("");
  jQuery("#edit-wo-other-observer-country").val("");
  jQuery("#edit-wo-other-observer-phone-number").val("");
  jQuery("#edit-wo-other-observer-mobile").val("");
  jQuery("#edit-wo-other-observer-email-id").val("");
}

function disableOtherObserverDetailsForm(flag) {
  var disabled = '';
  if (flag) {
    disabled = 'disabled';
  }
  jQuery("#edit-wo-other-observer-first-name").attr('disabled', disabled);
  jQuery("#edit-wo-other-observer-last-name").attr('disabled', disabled);
  jQuery("#edit-wo-other-observer-affiliation").attr('disabled', disabled);
  jQuery("#edit-wo-other-observer-address1").attr('disabled', disabled);
  jQuery("#edit-wo-other-observer-address2").attr('disabled', disabled);
  jQuery("#edit-wo-other-observer-city").attr('disabled', disabled);
  jQuery("#edit-wo-other-observer-region").attr('disabled', disabled);
  jQuery("#edit-wo-other-observer-country").attr('disabled', disabled);
  jQuery("#edit-wo-other-observer-phone-number").attr('disabled', disabled);
  jQuery("#edit-wo-other-observer-mobile").attr('disabled', disabled);
  jQuery("#edit-wo-other-observer-email-id").attr('disabled', disabled);
}

function setOtherObserverDetailsForm(details) {
  jQuery("#edit-wo-other-observer-first-name").val(details.fname);
  jQuery("#edit-wo-other-observer-last-name").val(details.lname);
  jQuery("#edit-wo-other-observer-affiliation").val(details.affiliation);
  jQuery("#edit-wo-other-observer-address1").val(details.address1);
  jQuery("#edit-wo-other-observer-address2").val(details.address2);
  jQuery("#edit-wo-other-observer-city").val(details.city);
  jQuery("#edit-wo-other-observer-region").val(details.region);
  jQuery("#edit-wo-other-observer-country").val(details.country);
  jQuery("#edit-wo-other-observer-phone-number").val(details.phoneno);
  jQuery("#edit-wo-other-observer-mobile").val(details.mobile);
  jQuery("#edit-wo-other-observer-email-id").val(details.email);
}

function getOtherObserverDetails(id) {
  resetOtherObserverDetailsForm();
  if (id == 0) {
    disableOtherObserverDetailsForm(false);
  } else {
    disableOtherObserverDetailsForm(true);
    jQuery("#edit-wo-select-other-observer-wrapper").addClass("loading");
    var url = Drupal.settings.basePath + 'observation/data/{"action":"getObserverDetails","params":{"observer_id":' + id + '}}';
    jQuery.getJSON(url, function(json){
      var observer_details = json.observer_details;
      setOtherObserverDetailsForm(observer_details);
      jQuery("#edit-wo-select-other-observer-wrapper").removeClass("loading");
    });
  }
}

function getRegionsForCountry(countryid, callbackFunc, callbackArg) {
  //jQuery("#edit-wo-region").val(0);
  //jQuery("#edit-wo-city").val(0);
  var ddlRegionID = "edit-wo-region";
  var ddlCityID = "edit-wo-city";
  jQuery("#" + ddlRegionID).removeOption(/./); // Clear up the regions drop down since it will be a new country
  jQuery("#" + ddlCityID).removeOption(/./); // Clear up the cities dropdown

  var ddRegions = jQuery("#" + ddlRegionID)[0];
  if (isNaN(countryid)) {
    ddRegions.disabled = true;
    jQuery("#" + ddlCityID)[0].disabled = true;
  } else {
    jQuery("#edit-wo-region-wrapper").addClass("loading");
    jQuery.getJSON(Drupal.settings.basePath + 'observation/data/{"action":"getRegionsForCountry","params":{"countryid":' + countryid + '}}', function(json){
      jQuery("#" + ddlRegionID).addOption(json.regions, false);
      if (ddRegions.length == 0) {
        ddRegions.disabled = true;
      } else {
        ddRegions.disabled = false;
        if (typeof(ddRegionDefaultValue) != 'undefined') {
          for (var i in json.regions) {
            if (json.regions[i] == ddRegionDefaultValue) {
              jQuery("#" + ddlRegionID).selectOptions(i, true);
              break;
            }
          }
        }
        else {
          selectOptionByText(jQuery('#' + ddlRegionID)[0], jQuery('#edit-wo-country').selectedOptions()[0].text);
        }
        getCitiesForRegion(jQuery("#" + ddlRegionID).selectedOptions()[0].value); // This needs to be done because the option 1 is selected by default but the change event is not fired.
      }
      jQuery("#edit-wo-region-wrapper").removeClass("loading");
      if (callbackFunc) {
        callbackFunc(callbackArg);
      }
    });
  }

  if (!featureAdded && mapportal.map) {
    mapportal.gotoAddress(jQuery('#edit-wo-country').selectedOptions()[0].text);
  }
}

function getCitiesForRegion(regionid, callbackFunc, callbackArg) {
  //jQuery("#edit-wo-region").val(regionid);
  //jQuery("#edit-wo-city").val(0);
  var ddlCityID = "edit-wo-city";
  jQuery("#" + ddlCityID).removeOption(/./); // Clear up the cities dropdown
  var ddCities = jQuery("#" + ddlCityID)[0];
  if (isNaN(regionid)) {
    ddCities.disabled = true;
  } else {
    jQuery("#edit-wo-city-wrapper").addClass("loading");
    jQuery.getJSON(Drupal.settings.basePath + 'observation/data/{"action":"getCitiesForRegion","params":{"regionid":' + regionid + '}}', function(json){
      jQuery("#" + ddlCityID).addOption(json.cities, false);
      if (ddCities.length == 0) {
        ddCities.disabled = true;
      } else {
        ddCities.disabled = false;
        //jQuery('#' + ddlCityID).addOption('0', jQuery('#edit-wo-region').selectedOptions()[0].text);
        jQuery('#' + ddlCityID).addOption('0', 'Select city');
        if (typeof(ddCityDefaultValue) != 'undefined') {
          for (var i in json.cities) {
            if (json.cities[i] == ddCityDefaultValue) {
              jQuery("#" + ddlCityID).selectOptions(i, true);
              break;
            }
          }
        }
        else {
        }
      }
      jQuery("#edit-wo-city-wrapper").removeClass("loading");
      if (callbackFunc) {
        callbackFunc(callbackArg);
      }
    });
  }

  if (!featureAdded && mapportal.map) {
    if (jQuery('#edit-wo-country').selectedOptions()[0].text != 'World' && jQuery('#edit-wo-region').selectedOptions()[0].text != 'World') {
      var addr = jQuery('#edit-wo-region').selectedOptions()[0].text + ',' + jQuery('#edit-wo-country').selectedOptions()[0].text;
      mapportal.gotoAddress(addr);
    }
  }
}

function onCitySelect() {
  if (!featureAdded && mapportal.map) {
    var addr = '';
    if (jQuery('#edit-wo-city').selectedOptions()[0].text == 'Select City') {
      addr = jQuery('#edit-wo-region').selectedOptions()[0].text + ',' + jQuery('#edit-wo-country').selectedOptions()[0].text;
    }
    else {
      addr = jQuery('#edit-wo-city').selectedOptions()[0].text + ',' + jQuery('#edit-wo-region').selectedOptions()[0].text + ',' + jQuery('#edit-wo-country').selectedOptions()[0].text;
    }
    mapportal.gotoAddress(addr);
  }
}
/*
function updateCityIDSelection(cityid) {
  jQuery("#edit-wo-city").val(cityid);
}
*/

function getAddressForFeatureAdded(address) {
  if (address.country != '') {
    if (jQuery('#edit-wo-country').selectedOptions()[0].text != address.country) {
      selectOptionByText(jQuery('#edit-wo-country')[0], address.country);
      if (address.region != '') {
        getRegionsForCountry(jQuery('#edit-wo-country').selectedOptions()[0].value, selectRegion, address);
      }
      else {
        getRegionsForCountry(jQuery('#edit-wo-country').selectedOptions()[0].value);
      }
    }
    else {
      if (address.region != '') {
        selectRegion(address);
      }
    }
  }
}

function selectRegion(address) {
  if (address.region != '') {
    if (jQuery('#edit-wo-region').selectedOptions()[0].text != address.region) {
      selectOptionByText(jQuery('#edit-wo-region')[0], address.region);
      if (address.city != '') {
        getCitiesForRegion(jQuery('#edit-wo-region').selectedOptions()[0].value, selectCity, address.city);
      }
      else {
        getCitiesForRegion(jQuery('#edit-wo-region').selectedOptions()[0].value);
      }
    }
    else {
      if (address.city != '') {
        selectCity(address.city);
      }
    }
  }
}

function selectCity(city) {
  if (city != '') {
    selectOptionByText(jQuery('#edit-wo-city')[0], city);
  }
}

function getChildEcosystems(parent_id) {
  var ddlChildEcosystemID = "edit-wo-child-ecosystem";
  jQuery("#" + ddlChildEcosystemID).removeOption(/./); // Clear up the child ecosystems drop down since it will be a new country

  var wrapper = jQuery("#edit-wo-child-ecosystem-wrapper");
  if (isNaN(parent_id)) {
    wrapper.hide();
    jQuery("#" + ddlCityID)[0].disabled = true;
  } else {
    wrapper.addClass("loading");
    jQuery.getJSON(Drupal.settings.basePath + 'observation/data/{"action":"getChildEcosystems","params":{"parent_id":' + parent_id + '}}', function(json){
      jQuery("#" + ddlChildEcosystemID).addOption(json.ecosystems, false);
      var ddChildEcosystems = jQuery("#" + ddlChildEcosystemID)[0];
      if (ddChildEcosystems.length == 0) {
        wrapper.hide();
      } else {
        wrapper.show();
        if (typeof(ddEcosystemDefaultValue) != 'undefined') {
          jQuery("#" + ddlChildEcosystemID).selectOptions(ddEcosystemDefaultValue.toString(), true);
        }
      }
      wrapper.removeClass("loading");
    });
  }

}

function addMoreCommonNamesUI() {
  var fs = jQuery(jQuery("#btn_add_more_common_names").parent().children()[0]).clone();

  // Remove the collapse-processed class from legend
  // It will be assigned when we call Drupal.attachBehaviors();
  fs.find("legend").removeClass("collapse-processed");

  var legendanc = fs.find("legend a");
  legendanc.html(legendanc.html() + " " + commonNamesCount);
  legendanc.parent().after(closeBtnHTML('removeCommonNameUI'));
  legendanc.parent().next().click(removeCommonNameUI);

  var txt_name = fs.find("#edit-wo-common-name");
  //txt_name.removeClass("required");
  txt_name.attr("id", txt_name.attr("id") + "-" + commonNamesCount);
  //txt_name.attr("name", txt_name.attr("name") + "_" + commonNamesCount);
  txt_name.val('');
  tooltip_common_name=(txt_name.parent().prev().find('.formInfo').find('a'));
  tooltip_common_name.attr("id",tooltip_common_name.attr("id")+ "-" + commonNamesCount);


  var sel_lang = fs.find("#edit-wo-common-name-language");
  sel_lang.attr("id", sel_lang.attr("id") + "-" + commonNamesCount);
  //sel_lang.attr("name", sel_lang.attr("name") + "_" + commonNamesCount);
  //sel_lang.val('');
  sel_lang.selectOptions("0");
  tooltip_sel_lang=(sel_lang.parent().prev().find('.formInfo').find('a'));
  tooltip_sel_lang.attr("id",tooltip_sel_lang.attr("id")+ "-" + commonNamesCount);


  var txt_region = fs.find("#edit-wo-common-name-region");
  txt_region.attr("id", txt_region.attr("id") + "-" + commonNamesCount);
  //txt_region.attr("name", txt_region.attr("name") + "_" + commonNamesCount);
  txt_region.val('');
  tooltip_region=(txt_region.parent().prev().find('.formInfo').find('a'));
  tooltip_region.attr("id",tooltip_region.attr("id")+ "-" + commonNamesCount);


  var sel_gender = fs.find("#edit-wo-common-name-gender");
  sel_gender.attr("id", sel_gender.attr("id") + "-" + commonNamesCount);
  //sel_gender.attr("name", sel_gender.attr("name") + "_" + commonNamesCount);
  sel_gender.selectOptions("0");

  tooltip_sel_gender=(sel_gender.parent().prev().find('.formInfo').find('a'));
  tooltip_sel_gender.attr("id",tooltip_sel_gender.attr("id")+ "-" + commonNamesCount);


  var sel_lifestage = fs.find("#edit-wo-common-name-lifestage");
  sel_lifestage.attr("id", sel_lifestage.attr("id") + "-" + commonNamesCount);
  //sel_lifestage.attr("name", sel_lifestage.attr("name") + "_" + commonNamesCount);
  sel_lifestage.selectOptions("0");

  tooltip_sel_lifestage=(sel_lifestage.parent().prev().find('.formInfo').find('a'));
  tooltip_sel_lifestage.attr("id",tooltip_sel_lifestage.attr("id")+ "-" + commonNamesCount);

  var txt_english = fs.find("#edit-wo-common-name-english");
  txt_english.attr("id", txt_english.attr("id") + "-" + commonNamesCount);
  txt_english.val('');
  
  tooltip_txt_english=(txt_english.parent().prev().find('.formInfo').find('a'));
  tooltip_txt_english.attr("id",tooltip_txt_english.attr("id")+ "-" + commonNamesCount);


  fs.insertBefore("#btn_add_more_common_names");

  commonNamesCount++;

  Drupal.attachBehaviors();

  jQuery('.alpha_space').keyup(onlyAlphaSpace);
  jQuery('select[name=wo_common_name_language]').change(showCommonNameEnglishSpellUI);

  jQuery(fs.find('legend').children()[0]).remove(); // hack for removing empty anchor which Drupal.attachBehaviors() adds in legend
  JT_init();
}

function removeCommonNameUI(evt) {
  var elem = jQuery(evt.currentTarget);
  var prev_len = elem.parent().parent().prevAll().length;
  elem.parent().parent().remove();

  var fieldsets = jQuery('#btn_add_more_common_names').prevAll(); // It returns in reverse sequence
  var len = fieldsets.length;
  if (prev_len != len) { // if it is not the last element
    for (var i = 0; i < len - 1; i++) {
      var fs = jQuery(fieldsets[i]);

      var inputs = fs.find('input');
      var sels = fs.find('select');

      var cnt = len - 1 - i;

      var legendanc = fs.find("legend a");
      legendanc.html(legendanc.html().substr(0, legendanc.html().lastIndexOf(' ')) + " " + cnt);

      var l = inputs.length;
      for (var j = 0; j < l; j++) {
        var inp = inputs[j];
        var id = inp.id;
        id = id.substr(0, id.lastIndexOf('-'));
        inp.id = id + '-' + cnt;
	tooltip_input_box=(jQuery(inp).parent().prev().find('.formInfo').find('a'));
	tooltip_input_box.attr("id",tooltip_input_box.attr("id")+ "-" + cnt);

      }

      l = sels.length;
      for (var j = 0; j < l; j++) {
        var sel = sels[j];
        var id = sel.id;
        id = id.substr(0, id.lastIndexOf('-'));
        sel.id = id + '-' + cnt;
	tooltip_dropdown=(jQuery(sel).parent().prev().find('.formInfo').find('a'));
	tooltip_dropdown.attr("id",tooltip_dropdown.attr("id")+ "-" + cnt);
      }
    }
  }
  commonNamesCount = len;
  return false;
}

/*
function dynamicSelectBoxForRegion() {
  jQuery("#edit-wo-region").hide();
  var sbx = document.createElement('select');
  sbx.id = 'edit-wo-region-select';
  jQuery(sbx).insertAfter("#edit-wo-region");
  jQuery(sbx).change(function() {
    getCitiesForRegion(parseInt(sbx.value));
  });
}

function dynamicSelectBoxForCity() {
  jQuery("#edit-wo-city").hide();
  var sbx = document.createElement('select');
  sbx.id = 'edit-wo-city-select';
  jQuery(sbx).insertAfter("#edit-wo-city");
  jQuery(sbx).change(function() {
    updateCityIDSelection(parseInt(sbx.value));
  });
}
*/

function submitObservation() {
  clearMessages();

  var data = new Object();

  data.observation_id = trim(getTextboxVal('edit-wo-observation_id'));
  data.topology = trim(getTextboxVal('edit-wo-topology'));
  if (data.topology == '') {
    displayMessage('error', 'Please enter geographical position on the map.');
    return false;
  }

  var common_names = [];

  var obj_cname = new commonname();
  obj_cname.name = trim(getTextboxVal('edit-wo-common-name'));
  if (obj_cname.name == '') {
    displayMessage('error', 'Please enter the common name.');
    return false;
  }
  /*
  obj_cname.language = trim(getTextboxVal('edit-wo-common-name-language'));
  if (obj_cname.name != '' && obj_cname.language == '') {
    displayMessage('error', 'Please enter the common name language.');
    return false;
  }
  */
  obj_cname.language = getDDSelectedText('edit-wo-common-name-language');
  obj_cname.region = trim(getTextboxVal('edit-wo-common-name-region'));
  if (obj_cname.name != '' && obj_cname.region == '') {
    displayMessage('error', 'Please enter the region in which the common name is used.');
    return false;
  }
  obj_cname.gender = getDDSelectedText('edit-wo-common-name-gender');
  obj_cname.lifestage = getDDSelectedText('edit-wo-common-name-lifestage');
  obj_cname.name_english = '';
  if (obj_cname.language.toLowerCase() != 'english') {
    obj_cname.name_english = trim(getTextboxVal('edit-wo-common-name-english'));
    if (obj_cname.name_english == '') {
      displayMessage('error', 'Please enter the english spelling of the common name entered.');
      return false;
    }
  }

  common_names.push(obj_cname);

  for (var i = 1; i < commonNamesCount; i++) {
    obj_cname = new commonname();

    obj_cname.name = trim(getTextboxVal('edit-wo-common-name-' + i));
    //obj_cname.language = trim(getTextboxVal('edit-wo-common-name-language-' + i));
    obj_cname.language = getDDSelectedText('edit-wo-common-name-language-' + i);
    obj_cname.region = trim(getTextboxVal('edit-wo-common-name-region-' + i));
    obj_cname.gender = getDDSelectedText('edit-wo-common-name-gender-' + i);
    obj_cname.lifestage = getDDSelectedText('edit-wo-common-name-lifestage-' + i);

    if (obj_cname.name != '' && obj_cname.region != '') {
      common_names.push(obj_cname);
    }
    else if (obj_cname.name == '' && obj_cname.region == '') { // just ignore all emtpy rows.
    }
    else {
      displayMessage('error', 'Please make sure you enter the name, language and the region in which the common name is used.');
      return false;
    }
    
    obj_cname.name_english = '';
    if (obj_cname.language.toLowerCase() != 'english') {
      obj_cname.name_english = trim(getTextboxVal('edit-wo-common-name-english-' + i));
      if (obj_cname.name_english == '') {
        displayMessage('error', 'Please enter the english spelling of the common name entered.');
        return false;
      }
    }
  }

  var scientific_name_info = new Object();
  scientific_name_info.s_name = trim(getTextboxVal('edit-wo-scientific-name'));
  scientific_name_info.s_author = trim(getTextboxVal('edit-wo-scientific-name-author'));
  scientific_name_info.s_year = trim(getTextboxVal('edit-wo-scientific-name-year'));
  if (!(scientific_name_info.s_name == '' && scientific_name_info.s_author == '' && scientific_name_info.s_year == '') && !(scientific_name_info.s_name != '' && scientific_name_info.s_author != '' && scientific_name_info.s_year != '')){
    displayMessage('error', 'Please make sure you enter the name, author and the year for scientific name.');
    return false;
  }
  if (scientific_name_info.s_year.length > 0 && scientific_name_info.s_year.length < 4) {
    displayMessage('error', 'Please enter correct year for scientific name.');
    return false;
  }

  var s_kingdom = trim(getTextboxVal('edit-wo-kingdom'));
  var s_phylum = trim(getTextboxVal('edit-wo-phylum'));
  var s_class = trim(getTextboxVal('edit-wo-class'));
  var s_order = trim(getTextboxVal('edit-wo-order'));
  var s_family = trim(getTextboxVal('edit-wo-family'));
  var s_genus = trim(getTextboxVal('edit-wo-genus'));
  var s_species = trim(getTextboxVal('edit-wo-species'));

  data.common_names = common_names;
  data.scientific_name_info = scientific_name_info;
  data.s_kingdom = s_kingdom;
  data.s_phylum = s_phylum;
  data.s_class = s_class;
  data.s_order = s_order;
  data.s_family = s_family;
  data.s_genus = s_genus;
  data.s_species = s_species;

  var ecosystem_id = jQuery('#edit-wo-parent-ecosystem').selectedOptions()[0].value;
  if ($('#edit-wo-child-ecosystem-wrapper').is(":visible")) {
    ecosystem_id = jQuery('#edit-wo-child-ecosystem').selectedOptions()[0].value;
  }

  data.ecosystem_id = ecosystem_id;

  data.nativeness = getDDSelectedText('edit-wo-nativeness');
  data.iucn_threat_category = getDDSelectedText('edit-wo-iucn-threat-category');

  data.record_language = trim(getTextboxVal('edit-wo-record-language'));
  // data.gender = getDDSelectedText('edit-wo-gender');
  // data.lifestage = getDDSelectedText('edit-wo-lifestage'); //trim(getTextboxVal('edit-wo-lifestage'));
  data.num_individuals = +trim(getTextboxVal('edit-wo-num-individuals'));
  if (data.num_individuals == 0) {
    data.num_individuals = 1;
  }

  var knwDateRange = false;
  if (isCheckboxChecked('edit-wo-know-date-range')) {
    knwDateRange = true;
  }
  data.is_date_range = +knwDateRange; // Convert boolean to integer

  if (knwDateRange) {
    var frmdt = trim(getTextboxVal('edit-wo-from-date'));
    if (frmdt == '') {
      displayMessage('error', 'Please enter start observation date.');
      return;
    }

    var todt = trim(getTextboxVal('edit-wo-to-date'));
    if (todt == '') {
      displayMessage('error', 'Please enter end observation date.');
      return;
    }

    if (new Date(todt) < new Date(frmdt)) {
      displayMessage('error', 'To date should be greater than from date.');
      return;
    }
    data.from_date = frmdt;
    data.to_date = todt;
  } else {
    var dt = trim(getTextboxVal('edit-wo-on-date'));
    if (dt == '') {
      displayMessage('error', 'Please enter observation date.');
      return;
    }
    data.on_date = dt;
  }

  var knwExactTime = false;
  if (isCheckboxChecked('edit-wo-know-exact-time')) {
    knwExactTime = true;
  }

  data.is_exact_time = +knwExactTime; // Convert boolean to integer
  if (knwExactTime) {
    data.at_time = getDDSelectedText('edit-wo-exact-time-hour') + ':' + getDDSelectedText('edit-wo-exact-time-minute') + ' ' + getDDSelectedText('edit-wo-exact-time-meridiem');
  } else {
    data.pod = getDDSelectedValues('edit-wo-part-of-day').join(',');
  }

  data.altitude = +trim(getTextboxVal('edit-wo-altitude'));
  data.depth = +trim(getTextboxVal('edit-wo-depth'));

  var obj_location = new location_details();
  obj_location.country = getDDSelectedText('edit-wo-country');
  if (jQuery('#edit-wo-region')[0].disabled) {
    obj_location.region = '';
  } else {
    obj_location.region = getDDSelectedText('edit-wo-region');
    if (obj_location.region == obj_location.country) {
      obj_location.region = '';
    }
  }
  if (obj_location.country == 'World') {
    obj_location.country = '';
  }
  if (jQuery('#edit-wo-city')[0].disabled) {
    obj_location.city = '';
  } else {
    obj_location.city = getDDSelectedText('edit-wo-city');
    if (obj_location.city == 'Select city') {
      obj_location.city = '';
    }
  }
  obj_location.locality = trim(getTextboxVal('edit-wo-locality'));
  if (obj_location.locality == '') {
    displayMessage('error', 'Please enter locality.');
    return false;
  }

  data.location = obj_location;

  var is_waterbody_related = isCheckboxChecked('edit-wo-haswaterbody');
  data.is_waterbody_related = +is_waterbody_related; // Convert boolean to integer
  if (is_waterbody_related) {
    var obj_waterbody = new waterbody();
    obj_waterbody.type = getDDSelectedText('edit-wo-waterbody-type');
    if (obj_waterbody.type.toLowerCase() == 'ocean') { // ignore country, region, city if ocean is selected.
      obj_location.country = '';
      obj_location.region = '';
      obj_location.city = '';
    }
    obj_waterbody.name = trim(getTextboxVal('edit-wo-waterbody-name'));
    if (obj_waterbody.name == '') {
      displayMessage('error', 'Please enter waterbody name.');
      return;
    }

    data.waterbody_info = obj_waterbody;
  }

  data.basis_of_record = getDDSelectedText('edit-wo-basis-of-record');

  data.taxanomic_status = getDDSelectedText('edit-wo-taxanomic-status');
  data.nomenclature_type_status = getDDSelectedText('edit-wo-nomenclature-type-status');

  var observer_type = parseInt(getRadioCheckedValue('wo_radio_observer'));
  var obj_observer = new Object();
  obj_observer.type = observer_type;
  if (observer_type != 0) {
    var observer_id = getDDSelectedValue('edit-wo-select-other-observer');
    obj_observer.id = observer_id;
    if (observer_id == 0) {
      var obj_obv_details = new observer_details();

      obj_obv_details.fname = trim(getTextboxVal('edit-wo-other-observer-first-name'));
      if (obj_obv_details.fname == '') {
        displayMessage('error', 'Please enter observer first name.');
        return;
      }
      obj_obv_details.lname = trim(getTextboxVal('edit-wo-other-observer-last-name'));
      if (obj_obv_details.lname == '') {
        displayMessage('error', 'Please enter observer last name.');
        return;
      }
      obj_obv_details.email = trim(getTextboxVal('edit-wo-other-observer-email-id'));
      obj_obv_details.affiliation = trim(getTextboxVal('edit-wo-other-observer-affiliation'));
      obj_obv_details.address1 = trim(getTextboxVal('edit-wo-other-observer-address1'));
      obj_obv_details.address2 = trim(getTextboxVal('edit-wo-other-observer-address2'));
      obj_obv_details.city = trim(getTextboxVal('edit-wo-other-observer-city'));
      obj_obv_details.region = trim(getTextboxVal('edit-wo-other-observer-region'));
      obj_obv_details.country = trim(getTextboxVal('edit-wo-other-observer-country'));
      obj_obv_details.phoneno = trim(getTextboxVal('edit-wo-other-observer-phone-number'));
      obj_obv_details.mobile = trim(getTextboxVal('edit-wo-other-observer-mobile'));
      if (obj_obv_details.mobile == '') {
        displayMessage('error', 'Please enter observer contact info.');
        return false;
      }

      obj_observer.details = obj_obv_details;
    }
  }
  data.observer = obj_observer;

  data.comments = trim(getTextboxVal('edit-wo-comments'));

  if(typeof(isValidate) !== 'undefined') {
    var validation = new Object();
    validation.status = getDDSelectedValue('edit-wo-select-validation-status');
    validation.comments = trim(getTextboxVal('edit-wo-validation-comments'));
    if (validation.comments == '') {
      displayMessage('error', 'Please enter validation comments.');
      return false;
    }
    data.validation = validation;

    if (validation.status == 1) { // if being approved, make sure all scientific info goes in.
      if (s_kingdom == '' || s_phylum == '' || s_class == '' || s_order == '' || s_family == '' || s_genus == '' || s_species == '') {
        displayMessage('error', 'Please make sure you have entered all scientific terms.');
        return false;
      }
    }
  }

  if (parseInt(data.observation_id) == 0) {
    var imgfile_elem = jQuery('#wo-imgfile');
    if (imgfile_elem.length > 0) {
      var img_fname = trim(imgfile_elem.val());
      if (img_fname == '') {
        displayMessage('error', 'Please select an image to upload.');
        return false;
      }
      else {
        if (!checkValidImageFile(img_fname)) {
          var msg = 'Only image files with following extensions are allowed.';
          msg += '<ul>';
          for (var i = 0; i < allowedImageExt.length; i++) {
            msg += '<li>' + allowedImageExt[i];
          }
          msg += '</ul>';
          displayMessage('error', msg);
          return false;
        }
      }
    }
  }

  data.captcha = trim(jQuery('#edit-wo-captcha').val());
  if (data.captcha == '') {
    displayMessage('error', 'Please enter the characters that you see in the captcha image.');
    return false;
  }

  var obj = new Object();
  obj.action = 'saveObservation';
  obj.params = data;
  var json_data = JSON.stringify(obj);

  var url = Drupal.settings.basePath + 'observation/data';
  jQuery.post(
    url,
    {request: json_data},
    function(data) {
      if (parseInt(data.error) == 1) {
        displayMessage('error', data.msg);
        return;
      } else {
        if (jQuery('#wo-fs-image').length > 0) {
          jQuery('#edit-wo-observation_id').val(data.observation_id);
          uploadImageForm(data.observation_id);
        }
        else {
          url = Drupal.settings.basePath + 'observation/' + data.observation_id;
          window.location.replace(url);
        }
      }
    },
    'json'
  );
}

function checkValidImageFile(filename) {
  var indx = filename.lastIndexOf('.');
  if (indx != -1) {
    var ext = filename.substr(indx + 1).toLowerCase();
    if (in_array(ext, allowedImageExt)) {
      return true;
    }
  }
  return false;
}

function uploadImageForm(observation_id) {
  var $frm = jQuery('#frm-image-upload');
  $frm.children().remove();

  var $file_elem = jQuery('#wo-imgfile');
  var $ui = $file_elem.clone(true);
  //$ui.val(jQuery('#wo-imgfile').val());
  $ui.attr('id', 'wo-imgfile1');

  $file_elem.hide();
  $ui.insertAfter($file_elem);

  $frm.append('<input name="request" id="request" type="hidden" />');
  $frm.append($file_elem);

  var data = new Object();

  data.action = 'uploadImage';
  var params = new Object();

  params.fileElem = 'wo_imgfile';
  params.observation_id = observation_id;
  params.copyright_text = jQuery('#edit-wo-image-copyright').val();

  data.params = params;

  var request_str = JSON.stringify(data);

  $frm.find('#request').val(request_str);

  $frm.submit();
}

function resetImageInputElem() {
  var $file_elem = jQuery('#wo-imgfile');
  var $dummy = jQuery('#wo-imgfile1');

  $file_elem.insertBefore($dummy);
  $file_elem.show();
  $dummy.remove();
}

// post-submit callback
function showImageUploadResponse(responseJSON, statusText)  {
  resetImageInputElem();
  jQuery(window).unload(deleteObservation);
  if (statusText == 'success') {
    if (responseJSON.error == 1) {
      return displayMessage('error', responseJSON.msg);
    } else {
      jQuery(window).unbind('unload');
      //return displayMessage('ok', responseJSON.msg);
      //url = window.location.href;
      url = Drupal.settings.basePath + 'observation/' + jQuery('#edit-wo-observation_id').val();
      window.location.replace(url);
    }
  } else {
    return displayMessage('error', statusText);
  }
}

function deleteObservation() {
  var oid = trim(getTextboxVal('edit-wo-observation_id'));
  var data = new Object();
  data.observation_id = oid;
  var obj = new Object();
  obj.action = 'deleteObservation';
  obj.params = data;
  var json_data = JSON.stringify(obj);

  var url = Drupal.settings.basePath + 'observation/data';
  jQuery.ajax({
    type: "POST",
    async: false,
    url: url,
    data: {request: json_data},
    success: function(data) {
      //alert(data);
    },
    error: function(data) {
      //alert(data);
    }
  });
}

function submitImageUploadForm() {
  var ajax_options = {
    //target:        '#output2',   // target element(s) to be updated with server response
    //beforeSubmit:  showRequest,  // pre-submit callback
    success:       showImageUploadResponse,  // post-submit callback
    dataType:  'json'        // 'xml', 'script', or 'json' (expected server response type)

    // other available options:
    //url:       url         // override for form's 'action' attribute
    //type:      type        // 'get' or 'post', override for form's 'method' attribute
    //clearForm: true        // clear all form fields after successful submit
    //resetForm: true        // reset the form after successful submit

    // jQuery.ajax options can be used here too, for example:
    //timeout:   3000
  };

  jQuery(this).ajaxSubmit(ajax_options);

  return false;
}

function keepMapInViewPort() {
  var $window = jQuery(window);
  var $mapArea = jQuery('#mapArea');

  if (mapAreaOrigTop == 0) {
    mapAreaOrigTop = $mapArea.offset().top;
  }

  var mapAreaTop = $mapArea.offset().top;

  var scrollTop = $window.scrollTop();
  if ((scrollTop + $mapArea.height()) < (jQuery('#edit-wo-submit').offset().top)) {
    var top = scrollTop - mapAreaOrigTop;
    if (top < 0) {
      top = 0;
    }
    $mapArea[0].style.top = top + 'px';
  }
}

function closeBtnHTML(cls) {
  var closebtnhtml = '';
  closebtnhtml += '<a href="#" class="' + cls + '" role="button" unselectable="on">';
  closebtnhtml += '  <span class="ui-icon ui-icon-closethick" unselectable="on" style="-moz-user-select: none;">close</span>';
  closebtnhtml += '</a>';
  return closebtnhtml;
}

function onlyNumeric() {
  var val = this.value.replace(/[^0-9\.]/g,''); // get only numbers and .
  var indx = val.indexOf('.');
  val = val.substr(0, indx + 1) + val.substr(indx + 1).replace('.', ''); // keep first . and remove all remaining .
  this.value = val;
}

function onlyInteger() {
  var val = this.value.replace(/[^0-9]/g,''); // get only numbers and .
  this.value = val;
}

function onlyAlphaSpace() {
  var val = this.value.replace(/[^a-zA-Z ]/g,''); // get only numbers and .
  this.value = val;
}

function onlyTillCurrentYear() {
  var val = this.value.replace(/[^0-9]/g,''); // get only numbers
  var d = new Date();
  var curr_year = parseInt(d.getFullYear());
  val = val.substr(0, 4);
  var a = val + '0000'.substr(0, 4 - val.length);
  if (parseInt(a) > curr_year) {
    val = val.substr(0, val.length - 1);
  }
  this.value = val;
}

function displayReminder() {
  var html = 'Please make sure that you have following information before attempting to contribute the record: \
            <ul>\
              <li>Common Name\
              <li>Langauge of Common Name\
              <li>Region where common name is used\
              <li>date of observation\
              <li>locality where observation was made\
              <li>language of the record (currently default as English)\
              <li>observer details (other than contributor)\
              <li>copyright information\
              <li>at least one photograph to upload\
            </ul>';
  
  displayMessage('warning', html);
}

function showCommonNameEnglishSpellUI(evt) {
  var sel = jQuery(evt.currentTarget);
  var elems = sel.parent().parent().nextAll();
  var spell_box = jQuery(elems[elems.length - 1]);
  if (sel.selectedOptions()[0].text.toLowerCase() == 'english') {
    spell_box.hide();
  }
  else {
    spell_box.show();
  }
}

function onChangeWaterbodyType() {
  hideCountryForOcean();
}

function hideCountryForOcean() {
  var show = true;
  if (isCheckboxChecked('edit-wo-haswaterbody')) {
    if (getDDSelectedText('edit-wo-waterbody-type') == 'Ocean') {
      show = false;
    }
  }
  
  if (show == true) {
    jQuery('#edit-wo-country-wrapper').show();
    jQuery('#edit-wo-region-wrapper').show();
    jQuery('#edit-wo-city-wrapper').show();
  }
  else {
    jQuery('#edit-wo-country-wrapper').hide();
    jQuery('#edit-wo-region-wrapper').hide();
    jQuery('#edit-wo-city-wrapper').hide();
  }  
}

function markPoint() {
  jQuery('#txtMPPtLat').val(jQuery('#txtMPPtLat_1').val());
  jQuery('#txtMPPtLon').val(jQuery('#txtMPPtLon_1').val());

  mapportal.markPoint();

  jQuery('#txtMPBBoxTLLat_1').val('');
  jQuery('#txtMPBBoxTLLon_1').val('');
  jQuery('#txtMPBBoxBRLat_1').val('');
  jQuery('#txtMPBBoxBRLon_1').val('');
}

function markBoundingBox() {
  jQuery('#txtMPBBoxTLLat').val(jQuery('#txtMPBBoxTLLat_1').val());
  jQuery('#txtMPBBoxTLLon').val(jQuery('#txtMPBBoxTLLon_1').val());
  jQuery('#txtMPBBoxBRLat').val(jQuery('#txtMPBBoxBRLat_1').val());
  jQuery('#txtMPBBoxBRLon').val(jQuery('#txtMPBBoxBRLon_1').val());

  mapportal.markBoundingBox();

  jQuery('#txtMPPtLat_1').val('');
  jQuery('#txtMPPtLon_1').val('');
}

function updateTopoTabsUI(topo) {
  if (jQuery('#tabsMapportal_1').length == 0) {
    return;
  }
  var re, matchedArr;
  if (mapportal.ctrl_pt.active) {
    jQuery('#tabsMapportal_1').tabs('option', 'selected', 0);
    re = new RegExp("(.*)[\(](.*)[ ](.*)[)]", "m");
    matchedArr = topo.match(re);
    jQuery("#txtMPPtLat_1").val(matchedArr[3]);
    jQuery("#txtMPPtLon_1").val(matchedArr[2]);
    jQuery("#txtMPBBoxTLLat_1").val("");
    jQuery("#txtMPBBoxTLLon_1").val("");
    jQuery("#txtMPBBoxBRLat_1").val("");
    jQuery("#txtMPBBoxBRLon_1").val("");
  } else if (mapportal.ctrl_bbox.active) {
    jQuery('#tabsMapportal_1').tabs('option', 'selected', 1);
    re = new RegExp("(.*)[\(][\(](.*)[ ](.*)[,](.*)[,](.*)[ ](.*)[,](.*)[,](.*)[)][)]", "m");
    matchedArr = topo.match(re);
    jQuery("#txtMPPtLat_1").val("");
    jQuery("#txtMPPtLon_1").val("");
    jQuery("#txtMPBBoxTLLat_1").val(matchedArr[3]);
    jQuery("#txtMPBBoxTLLon_1").val(matchedArr[2]);
    jQuery("#txtMPBBoxBRLat_1").val(matchedArr[6]);
    jQuery("#txtMPBBoxBRLon_1").val(matchedArr[5]);
  } else if (mapportal.ctrl_poly.active) {
    jQuery('#tabsMapportal_1').tabs('option', 'selected', 2);
    jQuery("#txtMPPtLat_1").val("");
    jQuery("#txtMPPtLon_1").val("");
    jQuery("#txtMPBBoxTLLat_1").val("");
    jQuery("#txtMPBBoxTLLon_1").val("");
    jQuery("#txtMPBBoxBRLat_1").val("");
    jQuery("#txtMPBBoxBRLon_1").val("");
  }
}

jQuery(document).ready(function(){
  // var frm = jQuery("#win-getObservations").clone();
  // jQuery("#win-getObservations").remove();
  // // Tweak. Put the observation form in the right place.
  // //frm.insertBefore('#mapArea');
  // /*
   // * The form being added at random place and then moving in
   // * to place would not look good. So it is hidden initially.
   // * After it is moved to correct place, show it.
   // */
  // jQuery("#win-getObservations").show();
  // Attach Drupal behaviors for collapsible fieldset and resizable textarea.
  Drupal.attachBehaviors();

  if (typeof mapportal.onMapInitComplete == "boolean") {
    onMapInitComplete();
  }
  else {
    mapportal.onMapInitComplete = onMapInitComplete;
  }
  mapportal.onFeatureAdded = onFeatureAddedOnMap;
  mapportal.getAddressForFeature = getAddressForFeatureAdded;
  mapportal.onUpdateTabsUI = updateTopoTabsUI;

  //dynamicSelectBoxForRegion();
  //dynamicSelectBoxForCity();

  var $pod = jQuery('#edit-wo-part-of-day');
  if ($pod.length > 0) {
    if ($pod[0].options.length > 0) {
      if ($pod.selectedOptions().length == 0) {
        $pod[0].options[0].selected = true;
      }
    }
  }

  toggleOtherObserverDetails(parseInt(getRadioCheckedValue('wo_radio_observer')));
  if (jQuery('#edit-wo-select-other-observer').selectedOptions().val() != 0) {
    disableOtherObserverDetailsForm(true);
  }
  toggleExactDate(isCheckboxChecked('edit-wo-know-date-range'));
  toggleExactTime(isCheckboxChecked('edit-wo-know-exact-time'));
  toggleWaterbodyInfo(isCheckboxChecked('edit-wo-haswaterbody'));
  jQuery('#edit-wo-waterbody-type').change(onChangeWaterbodyType);
  hideCountryForOcean();

  getRegionsForCountry(parseInt(jQuery("#edit-wo-country").selectedValues()[0]));
  getChildEcosystems(parseInt(jQuery("#edit-wo-parent-ecosystem").selectedValues()[0]));

  jQuery(".datepicker").datepicker({
    showOn: 'button',
    buttonImage: Drupal.settings.basePath + 'sites/all/modules/win_observation/images/calendar.gif',
    buttonImageOnly: true,
    changeMonth: true,
    changeYear: true,
		yearRange: '-100:+100', // Range of years to display in drop-down,
    //dateFormat: 'dd-mm-yy',
    dateFormat: 'M dd, yy',
    maxDate: '+0M +0D'
  });

  /*
  var autoCompleteURL = Drupal.settings.basePath + 'observation/data';
  var request = '{"action":"getAutoCompleteValues"}';
  $("#edit-wo-kingdom").autocomplete(autoCompleteURL, {
		width: 260,
		selectFirst: false
	});
  */

  // Hack for image upload
  // bind to the form's submit event
  jQuery('#frm-image-upload').submit(submitImageUploadForm);

  if(typeof(isValidate) !== 'undefined') {
  }
  else {
    jQuery(window).scroll(keepMapInViewPort);
  }
  
  jQuery('.removeCommonNameUI').click(removeCommonNameUI);

  jQuery('.numeric').keyup(onlyNumeric);
  jQuery('.integer').keyup(onlyInteger);
  jQuery('.alpha_space').keyup(onlyAlphaSpace);
  jQuery('.till_current_year').keyup(onlyTillCurrentYear);
  
  jQuery('select[name=wo_common_name_language]').change(showCommonNameEnglishSpellUI);
  
  if (trim(getTextboxVal('edit-wo-observation_id')) == '0') { // New observation
    displayReminder();
  }
  
  if (jQuery("#tabsMapportal_1").length > 0) {
    jQuery("#tabsMapportal_1").tabs();
    //v//jQuery("#txtMPAddress").watermark("Enter address");
    jQuery("#btnMPPt_1").click(markPoint);
    jQuery("#btnMPBBox_1").click(markBoundingBox);

    //jQuery(".close-map-tabs a").click(hideTabs);
    //hideTabs();
  }
});